package com.one.blocks.trace.config;

import com.one.blocks.common.util.SnowflakeIdGen;
import com.one.blocks.trace.config.properties.TraceProperties;
import com.one.blocks.trace.interceptor.TraceInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.CollectionUtils;
import org.springframework.web.servlet.config.annotation.InterceptorRegistration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * @author linfuxin Created on 2022-02-14 10:51:37
 */
@Configuration
@EnableConfigurationProperties(TraceProperties.class)
@ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.SERVLET)
public class TraceAutoConfig implements WebMvcConfigurer {

    @Autowired
    private TraceProperties traceProperties;
    @Bean
    public SnowflakeIdGen snowflakeIdGen() {
        return new SnowflakeIdGen(traceProperties.getDataCenterId(), traceProperties.getMachineId());
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        InterceptorRegistration interceptorRegistration = registry.addInterceptor(new TraceInterceptor(snowflakeIdGen()))
                .order(0)
                .addPathPatterns("/**");
        if (!CollectionUtils.isEmpty(traceProperties.getExcludePatterns())) {
            interceptorRegistration.excludePathPatterns(traceProperties.getExcludePatterns());
        }
    }
}